#include "auxilary.h"

Point2D operator - ( const Point2D & p1, const Point2D & p2 )
{
    return Point2D ( p1.x - p2.x, p1.y - p2.y );
}

Point2D operator * ( const Point2D & p1, double factor )
{
    return Point2D ( p1.x * factor, p1.y * factor );
}

double Angle ( const Point2D & p1, const Point2D & p2 )
{
    Point2D p3 = p2 - p1;
    double ang = atan ( p3.y / p3.x );
    if ( p3.x < 0 )
        return ang + PI;
    if ( ang < 0 )
        return ang + 2 * PI;
    return ang;
}

double Distance ( const Point2D & p1, const Point2D & p2 )
{
    return sqrt ( sqr ( p1.x - p2.x ) + sqr ( p1.y - p2.y ));
}

QString SaveVector ( const QString fileName, const QVector<double> & vect )
{
    QFile file ( fileName );
    if ( ! file.open ( QIODevice::WriteOnly ))
        return "Save vector: Cannot open file \"" + fileName + "\" for writing.";

    QTextStream out ( & file );
    for ( size_t i = 0; i < vect.size(); ++i )
    {
        out << QString::number ( vect[i], 'g', 8 ) << "\n";
    }
    file.close();
    return "";
}

QString SavePointVector ( const QString fileName, const QVector<Point2D> & vect )
{
    QFile file ( fileName );
    if ( ! file.open ( QIODevice::WriteOnly ))
        return "Save vector: Cannot open file \"" + fileName + "\" for writing.";

    QTextStream out ( & file );
    for ( size_t i = 0; i < vect.size(); ++i )
    {
        out << QString::number ( vect[i].x, 'g', 8 ) << "\t" << QString::number ( vect[i].y, 'g', 8 ) << "\n";
    }
    file.close();
    return "";
}

double Rand()
{
    return qrand() / (double) RAND_MAX;
}
